#include "dkglMaterial.h"
#include "dkglUtility.h"

namespace DKGL
{

	using namespace std;

	Material::Material(const String& name):
		_name(name),
		_enableLighting(false),
		_hasTexture(false),
		_enableDepthTest(true),
		_enableBlend(false),
		_frontFaceWinding(FFW_CCW),
		_renderMode(RM_POLYGON)
	{
		_initDefaultVal();
	}

	
	Material::Material(const Material& m)
	{
		/*mName		= m.mName;
		mAmbient	= m.mAmbient;
		mDiffuse		= m.mDiffuse;
		mSpecular	= m.mSpecular;
		m_fExp		= m.m_fExp;*/
	}
	
	Material::~Material()
	{}

	void Material::setColor(float r, float g, float b)
	{
		_color.r = r;
		_color.g = g;
		_color.b = b;
	}


	void Material::setColor(const Colorf& color)
	{
		_color = color;
	}


	void Material::setTexture(TexturePtr texturePtr)
	{
		_texturePtr = texturePtr;
		_hasTexture = true;
	}

	void Material::_initDefaultVal()
	{
		for(int i=0;i<3;i++)
		{
			mAmbient.rgb[i] = 0.0f;
			mDiffuse.rgb[i] = 0.0f;
			mSpecular.rgb[i] = 0.0f;
		}
		m_fExp = 50;
	}

	Material& Material::setAmbient(const Colorf& amb)
	{
		mAmbient = amb;
		return *this;
	}
	
	Material& Material::setAmbient(float r, float g, float b, float a)
	{
		mAmbient = Colorf(r, g, b, a);
		return *this;
	}

	Material& Material::setDiffuse(const Colorf& diff)
	{
		mDiffuse = diff;
		return *this;
	}

	Material& Material::setDiffuse(float r, float g, float b, float a)
	{
		mDiffuse = Colorf(r, g, b, a);
		return *this;
	}
		
	Material& Material::setSpecular(const Colorf& spec, float exp)
	{
		mSpecular = spec;
		m_fExp = exp;
		return *this;
	}
		
	Material& Material::setSpecular(float r, float g, float b, float a, float exp)
	{
		mSpecular = Colorf(r, g, b, a);
		m_fExp = exp;
		return *this;
	}

	void Material::begin()
	{
		/*glMaterialfv(GL_FRONT, GL_AMBIENT,   mAmbient.rgba); 
		glMaterialfv(GL_FRONT, GL_DIFFUSE,   mDiffuse.rgba); 
		glMaterialfv(GL_FRONT, GL_SPECULAR,  mSpecular.rgba); 
		glMaterialf (GL_FRONT, GL_SHININESS, m_fExp); */

		glDisable(GL_LIGHTING);
		glColor3fv(_color.rgb);

		if (_hasTexture)
		{
			glEnable(GL_TEXTURE_2D);
			_texturePtr->bind();
		}
		else
		{
			glDisable(GL_TEXTURE_2D);
		}

		if (_enableDepthTest)
		{
			glEnable(GL_DEPTH_TEST);
		}
		else
		{
			glDisable(GL_DEPTH_TEST);
		}

		if (_frontFaceWinding == FFW_CW)
		{
			glFrontFace(FFW_CW);
		}
		else
		{
			glFrontFace(FFW_CCW);
		}

		glPolygonMode( GL_FRONT_AND_BACK, _renderMode);
	}

	void Material::end()
	{

	}
}